﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using Tomato.Helpers;

namespace Tomato.Authentication
{
    public class CookieAuthenticator
    {
        private const string AuthenticationCookie = "AuthenticationCookie";
        private const string CookieRemoved = "CookieRemoved";


        public static void SignIn(Controller controller, object data, TimeSpan timeSpan)
        {
            HttpCookie cookie = new HttpCookie(AuthenticationCookie, data.ToJsonBase64());
            cookie.Expires = DateTime.Now.Add(timeSpan);
            controller.Response.Cookies.Add(cookie);
            controller.Session.Remove(CookieRemoved);
        }

        public static bool IsSigneIn(Controller controller)
        {
            return controller.Session[CookieRemoved] == null && controller.Request.Cookies[AuthenticationCookie] != null;
        }

        public static T GetSignInData<T>()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[AuthenticationCookie];
            if (cookie == null)
            {
                return default(T);
            }
            else
            {
                string s = cookie.Value;
                T data = string.IsNullOrEmpty(s) ? default(T) : s.JsonBase64ToObject<T>();
                return data;
            }
        }

        public static T GetSignInData<T>(Controller controller)
        {
            HttpCookie cookie = controller.Request.Cookies[AuthenticationCookie];
            if (cookie == null)
            {
                return default(T);
            }
            else
            {
                string s = cookie.Value;
                T data = string.IsNullOrEmpty(s) ? default(T) : s.JsonBase64ToObject<T>();
                controller.Session[AuthenticationCookie] = data;
                return data;
            }
        }

        public static void SignOff(Controller controller)
        {
            HttpCookie cookie = controller.Request.Cookies[AuthenticationCookie];
            if (cookie != null)
            {
                cookie.Expires = TimeHelper.GetDistantPast();
                cookie.Value = null;
                controller.Response.Cookies.Set(cookie);
                controller.Session[CookieRemoved] = true;
                controller.Session.Remove(AuthenticationCookie);

            }
        }
    }
}
